<template>
    <div>
        <rui-page :defines="defines">
            <rui-table :defineId="'userCollocation'"
                       :slots="[{key:'lockFlag',slot:'lockFlag'},{key:'action',slot:'action'}]"
                       :select="false"
                       :showIndex="false"
                       @loadDatas="getUserList"
                       ref="memberInfoTable">
                <template slot-scope="{ row, index }" slot="lockFlag">
                    <div v-if="row.lockFlag === '0'">
                        <Tag color="success" size="default">启用</Tag>
                    </div>
                    <div v-else>
                        <Tag color="error" size="default">禁用</Tag>
                    </div>
                </template>
                <template slot="action" slot-scope="{ row }">
                    <div>
                        <Button @click="edit(row)" size="small" type="primary">编辑</Button>
                    </div>
                </template>
            </rui-table>
        </rui-page>
        <div class="changeRemarksClass">
            <Modal :title="modalTitle" v-model="memberModalVisible" :mask-closable='false' :width="500"
                   :styles="{top: '80'}">
                <Form ref="memberForm" :model="memberForm" :label-width="75" :rules="memberFormValidate">
                    <FormItem label="岗位状态" prop="postStatus">
                        <Select v-model="memberForm.postStatus" clearable @on-change="checkChangeRemarks">
                            <Option v-for="item in postStatusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                        </Select>
                    </FormItem>
                    <div v-show="show">
                        <FormItem label="离岗原因" prop="changeRemarks" :rules="memberForm.changeRemarksRequired?changeRemarksCheck:changeRemarksVerify">
                            <Input v-model="memberForm.changeRemarks"/>
                        </FormItem>
                    </div>
                    <FormItem label="代理人" prop="proxy">
                        <div style="display:flex;">
                            <Input v-model="memberForm.proxy" readonly placeholder="请选择" />
                            <Button type="info" @click="searchName">请选择</Button>
                            <Button icon="md-trash" @click="clearSelectDep">清空已选</Button>
                        </div>
                    </FormItem>
                    <FormItem label="组长" prop="headman">
                        <div style="display:flex;">
                            <Input v-model="memberForm.headman" readonly  placeholder="请选择" />
                            <Button type="info" @click="searchGroupLeader">请选择</Button>
                            <Button icon="md-trash" @click="clearGroupLeader">清空已选</Button>
                        </div>
                    </FormItem>
                    <FormItem label="代理组长" prop="chargeHand">
                        <div style="display:flex;">
                            <Input v-model="memberForm.chargeHand" readonly  placeholder="请选择" />
                            <Button type="info" @click="searchAgentGroupLeader">请选择</Button>
                            <Button icon="md-trash" @click="clearAgentGroupLeader">清空已选</Button>
                        </div>
                    </FormItem>
                </Form>
                <div slot="footer">
                    <Button type="text" @click="cancelUser">取消</Button>
                    <Button type="primary" :loading="submitLoading" @click="submitUser">提交</Button>
                </div>
            </Modal>
        </div>
        <staffChoice :value="taskHandlerChangeVisible" @cancel="cancelTaskHandler" @afterSubmit="afterChangeOwner"/>
        <staffChoice :value="groupLeaderVisible" @cancel="cancelGroupLeader" @afterSubmit="getGroupLeader"/>
        <staffChoice :value="agentGroupLeaderVisible" @cancel="cancelAgentGroupLeader" @afterSubmit="getAgentGroupLeader"/>
    </div>
</template>
<script>
    import * as utils from '_p/afs-apply/assets/js/utils.js'
    import userCollocation from "../user-collocation/defines/userCollocation";
    import {
        getUserListData
    } from "@/projects/basic/api/admin/user";
    import {
        initDepartment,
        loadDepartment,
        searchDepartment
    } from "@/projects/basic/api/admin/department";
    import {
        getAllRoleList
    } from "@/projects/basic/api/admin/role";
    import {setUserCollocation,queryUserCollocation,savePostChangeLog} from "@/projects/afs-core-business/api/afs-case/parameter-rules/group";
    import {getUserDetailsInfo} from "@/projects/afs-core-business/api/afs-case/parameter-rules/group";
    import {deepClone} from "../../../../../../libs/utils/ObjectClone";
    import staffChoice from "@/projects/afs-core-business/pages/case/parameter-rules/user-collocation/staffChoice";
    export default {
        components: {
            staffChoice
        },
        data() {
            let validate = function(rule, value, callback) {
                if (value==="") {
                    return callback("岗位不能为空")
                }
                return callback();
            };
            let totalWeight = function(rule, value, callback) {
                if (value===""||value===undefined) {
                    return callback("权重不能为空")
                }
                return callback();
            };
            let agentValidate = function(rule, value, callback) {
                if (value===""||value==="undefined,undefined") {
                    return callback("代理人不能为空")
                }
                return callback();
            };
            let groupLeader = function(rule, value, callback) {
                if (value===""||value==="undefined,undefined") {
                    return callback("组长不能为空")
                }
                return callback();
            };
            let agentGroupLeader = function(rule, value, callback) {
                if (value===""||value==="undefined,undefined") {
                    return callback("代理组长不能为空")
                }
                return callback();
            };
            return{
                loading: true,
                dpLoading: false, // 部门树加载
                operationLoading: false,
                importLoading: false,
                loadingExport: true,
                drop: false,
                dropDownContent: "展开",
                dropDownIcon: "ios-arrow-down",
                selectCount: 0,
                selectList: [],
                viewImage: false,
                deptId: [],
                selectDep: [],
                department: [],
                dataDep: [],
                searchKey: "",
                searchForm: {
                    username: "",
                    deptId: "",
                    phone: "",
                    userEmail: "",
                    lockFlag: "",
                    pageNumber: 1,
                    pageSize: 10,
                    startDate: "",
                    endDate: "",
                    userRealName:"",
                    postStatus:"",
                    userName:"",
                    approvalAuthority:"03",
                },
                modalTitle:"",
                memberModalVisible:false,
                memberForm: {
                    userId:"",
                    totalWeight: "",
                    postStatus:"",
                    agent:"",
                    agentId:"",
                    groupLeader:"",
                    groupLeaderId:"",
                    agentGroupLeader:"",
                    agentGroupLeaderId:"",
                    loginName:"",
                    agentLoginName:"",
                    groupLeaderLoginName:"",
                    agentGroupLeaderLoginName:"",
                    approvedAmount:"",
                    roleIds:"",
                    changeRemarks:"",
                    changeRemarksRequired:false,
                    proxy:"",
                    headman:"",
                    chargeHand:"",
                },
                logForm:{
                    userId:"",
                    userName:"",
                    postChangeStatus:"",
                    changeRemarks:"",
                    loginName:"",
                },
                submitLoading: false,
                userList:[],
                postStatusList:[
                    {
                        value: '0',
                        label: '离岗'
                    },
                    {
                        value: '1',
                        label: '在岗'
                    },
                ],
                memberFormValidate: {
                    // postStatus: [
                    //     { required: true, message: '岗位状态不能为空', trigger: 'change' }
                    // ],
                    // totalWeight: [
                    //     { required: true, validator: totalWeight, trigger: 'change' }
                    // ],
                    // agent: [
                    //     { required: true, validator: agentValidate, trigger: 'change' }
                    // ],
                    // groupLeader: [
                    //     {required: true, validator: groupLeader, trigger: "change"}
                    // ],
                    // agentGroupLeader: [
                    //     {required: true, validator: agentGroupLeader, trigger: "change"}
                    // ],
                    // approvedAmount: [
                    //     { required: true, message: '审批金额不能为空', trigger: 'change' },
                    //     {validator:(rule,value,callback)=>{utils.isTwoDicmalValiate(rule,value,callback)},trigger:"blur"}
                    // ],
                },
                total:"",
                userNameForm: {
                    pageNumber: 1,
                    pageSize: 5,
                },
                pageNumber: 1,
                pageSize: 5,
                mainUserName:"",
                groupLeaderName:"",
                agentGroupLeaderName:"",
                param:{
                    userId:"",
                    totalWeight: "",
                    postStatus:"",
                    agent:"",
                    groupLeader:"",
                    agentGroupLeader:""
                },
                show:false,
                changeRemarksCheck: [
                    {required: false}
                ],
                changeRemarksVerify: [
                    {required: true, message: "岗位原因不能为空", trigger: "change"}
                ],
                diasabledInput: false,
                postFlag:"",
                taskHandlerChangeVisible:false,
                groupLeaderVisible:false,
                agentGroupLeaderVisible:false,
            }
        },
        methods: {
            init() {
                this.initDepartmentData();
                this.getUserList(1,10);
                this.initDepartmentTreeData();
                this.getUserNameList();
            },
            dropDown() {
                if (this.drop) {
                    this.dropDownContent = "展开";
                    this.dropDownIcon = "ios-arrow-down";
                } else {
                    this.dropDownContent = "收起";
                    this.dropDownIcon = "ios-arrow-up";
                }
                this.drop = !this.drop;
            },
            initDepartmentData() {
                initDepartment().then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.value = e.id;
                                e.label = e.title;
                                e.loading = false;
                                e.children = [];
                            } else {
                                e.value = e.id;
                                e.label = e.title;
                            }
                            if (e.status === '0') {
                                e.label = "[已禁用] " + e.label;
                                e.disabled = true;
                            }
                        });
                        this.department = res.data;
                    }
                });
            },
            getUserList(pageNumber, pageSize) {
                // 多条件搜索用户列表
                this.loading = true;
                this.searchForm.pageNumber = pageNumber;
                this.searchForm.pageSize = pageSize;
                getUserDetailsInfo(this.searchForm).then(res=>{
                    if(res.code === "0000"){
                        let {records, total} = res.data;
                        this.$refs.memberInfoTable.updateTableData(records, total);
                    }
                })
            },
            initDepartmentTreeData() {
                initDepartment().then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.loading = false;
                                e.children = [];
                            }
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                        });
                        this.dataDep = res.data;
                    }
                });
            },
            getRoleList() {
                getAllRoleList().then(res => {
                    if (res.code === "0000") {
                        this.roleList = res.data;
                    }
                });
            },
            loadData(item, callback) {
                item.loading = true;
                loadDepartment(item.value).then(res => {
                    item.loading = false;
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.value = e.id;
                                e.label = e.title;
                                e.loading = false;
                                e.children = [];
                            } else {
                                e.value = e.id;
                                e.label = e.title;
                            }
                            if (e.status === '0') {
                                e.label = "[已禁用] " + e.label;
                                e.disabled = true;
                            }
                        });
                        item.children = res.data;
                        callback();
                    }
                });
            },
            loadDataTree(item, callback) {
                loadDepartment(item.id).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.loading = false;
                                e.children = [];
                            }
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                        });
                        callback(res.data);
                    }
                });
            },
            searchDp() {
                // 搜索部门
                if (this.searchKey) {
                    this.dpLoading = true;
                    searchDepartment({title: this.searchKey}).then(res => {
                        this.dpLoading = false;
                        if (res.code === "0000") {
                            res.data.forEach(function (e) {
                                if (e.status === '0') {
                                    e.title = "[已禁用] " + e.title;
                                    e.disabled = true;
                                }
                            });
                            this.dataDep = res.data;
                        }
                    });
                } else {
                    this.initDepartmentTreeData();
                }
            },
            selectTree(v) {
                if (v.length > 0) {
                    // 转换null为""
                    for (let attr in v[0]) {
                        if (v[0][attr] === null) {
                            v[0][attr] = "";
                        }
                    }
                    let str = JSON.stringify(v[0]);
                    let data = JSON.parse(str);
                    this.userForm.deptId = data.id;
                    this.userForm.departmentTitle = data.title;
                }
            },
            handleChangeDep(value, selectedData) {
                // 获取最后一个值
                if (value && value.length > 0) {
                    this.searchForm.deptId = value[value.length - 1];
                } else {
                    this.searchForm.deptId = "";
                }
            },
            changePage(v) {
                this.searchForm.pageNumber = v;
                this.getUserList(1,10);
                this.clearSelectAll();
            },
            changePageSize(v) {
                this.searchForm.pageSize = v;
                this.getUserList(1,10);
            },
            selectDateRange(v) {
                if (v) {
                    this.searchForm.startDate = v[0];
                    this.searchForm.endDate = v[1];
                }
            },
            handleSearch() {
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.getUserList(1,10);
            },
            handleReset() {
                this.$refs.searchForm.resetFields();
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.selectDate = null;
                this.searchForm.startDate = "";
                this.searchForm.endDate = "";
                this.selectDep = [];
                this.searchForm.deptId = "";
                this.searchForm.userName = "";
                this.searchForm.paramStatus = "";
                // 重新加载数据
                this.getUserList(1,10);
            },
            changeSort(e) {
                this.searchForm.sort = e.key;
                this.searchForm.order = e.order;
                if (e.order === "normal") {
                    this.searchForm.order = "";
                }
                this.getUserList(1,10);
            },
            //编辑
            edit(row){
                this.memberForm.userId = row.userId;
                this.logForm.userId = row.userId;
                this.logForm.userName = row.userRealName;
                this.modalTitle = "用户配置";
                this.$refs.memberForm.resetFields();
                // 转换null为""
                for (let attr in row) {
                    if (row[attr] === null) {
                        row[attr] = "";
                    }
                }
                let str = JSON.stringify(row);
                let member = JSON.parse(str);
                if(row.postStatus === "0"){
                    this.show = false;
                    this.memberForm.changeRemarksRequired = true;
                }else{
                    this.show = false;
                    this.memberForm.changeRemarksRequired = true;
                }
                this.memberForm.postStatus = row.postStatus;
                this.memberForm.totalWeight = row.totalWeight;
                this.postFlag = row.postStatus;
                if(row.approvedAmount!=null&&row.approvedAmount!=undefined){
                    this.memberForm.approvedAmount = row.approvedAmount.toString();
                }
                if(row.agent!==undefined && row.agent!==""){
                    this.mainUserName = row.agent;
                    this.memberForm.agent = row.agentLoginName+','+row.agent;
                    this.memberForm.agentLoginName=row.agentLoginName;
                    this.memberForm.proxy=row.agent;
                }else if(row.agent===undefined){
                    this.memberForm.agent ="";
                    this.mainUserName ="";
                    this.memberForm.agentId="";
                    this.memberForm.agentLoginName = "";
                }
                if(row.groupLeader!==undefined && row.groupLeader!==""){
                    this.groupLeaderName = row.groupLeader;
                    this.memberForm.groupLeader = row.groupLeaderLoginName+','+row.groupLeader;
                    this.memberForm.groupLeaderLoginName = row.groupLeaderLoginName;
                    this.memberForm.headman=row.groupLeader;
                    this.memberForm.chargeHand=row.agentGroupLeader;
                }else if(row.groupLeaderName===undefined){
                    this.memberForm.groupLeader ="";
                    this.groupLeaderName = "";
                    this.memberForm.groupLeaderId = "";
                    this.memberForm.groupLeaderLoginName = "";
                }
                if(row.agentGroupLeader!==undefined && row.agentGroupLeader!==""){
                    this.memberForm.chargeHand=row.agentGroupLeader;
                    this.agentGroupLeaderName = row.agentGroupLeader;
                    this.memberForm.agentGroupLeader = row.agentGroupLeaderLoginName+','+row.agentGroupLeader;
                    this.memberForm.agentGroupLeaderLoginName = row.agentGroupLeaderLoginName;
                }else if(row.agentGroupLeader===undefined){
                    this.memberForm.agentGroupLeader ="";
                    this.agentGroupLeaderName = "";
                    this.memberForm.agentGroupLeaderId = "";
                    this.memberForm.agentGroupLeaderLoginName = "";
                }
                this.memberForm.loginName = row.username;
                this.memberModalVisible = true;
            },
            cancelUser() {
                this.memberModalVisible = false;
            },
            submitUser() {
                this.$refs.memberForm.validate(valid => {
                    if(valid){
                        let self = this;
                        self.logForm.postChangeStatus = this.memberForm.postStatus;
                        let value = this.memberForm;
                        setUserCollocation(this.memberForm).then(res=>{
                            if(res.code === "0000"){
                                this.$Message.success("操作成功");
                                this.saveLog();
                                this.memberForm.agent = "";
                                this.memberForm.groupLeader = "";
                                this.memberForm.agentGroupLeader = "";
                                this.memberForm.agentId = "";
                                this.memberForm.groupLeaderId = "";
                                this.memberForm.agentGroupLeaderId = "";
                                this.memberForm.mainUserName = "";
                                this.memberForm.groupLeaderName = "";
                                this.memberForm.agentGroupLeaderName = "";
                                this.memberForm.agentLoginName = "";
                                this.memberForm.groupLeaderLoginName = "";
                                this.memberForm.agentGroupLeaderLoginName = "";
                                this.memberModalVisible = false;
                            }
                        })
                    }
                })
            },
            saveLog(){
                this.logForm.changeRemarks = this.memberForm.changeRemarks;
                this.logForm.loginName = this.memberForm.loginName;
                savePostChangeLog(this.logForm).then(res=>{
                    if(res.code === "0000"){
                        this.getALLUserList();
                    }
                })
            },
            //获取用户名称
            getUserNameList(){
                let params = "";
                params = {
                    pageNumber: this.pageNumber,
                    pageSize: this.pageSize,
                };
                getUserListData(params).then(res => {
                    if (res.code === "0000") {
                        let self = this;
                        this.userList = res.data.records;
                        this.total = res.data.total;
                    }
                })
            },
            changePageName(v) {
                this.pageNumber = v;
                this.getUserNameList();
            },
            changePageSizeName(v) {
                this.pageSize = v;
                this.getUserNameList();
            },
            checkValue(v){
                if(v){
                    this.memberForm.agent=v.value+","+v.label;
                    this.mainUserName = v.label;
                }
            },
            groupLeaderValue(v){
                if(v){
                    this.memberForm.groupLeader=v.value+","+v.label;
                    this.groupLeaderName = v.label;
                }
            },
            agentGroupLeaderNameValue(v){
                if(v){
                    this.memberForm.agentGroupLeader = v.value+","+v.label;
                    this.agentGroupLeaderName = v.label;
                }
            },
            getALLUserList() {
                // 多条件搜索用户列表
                this.loading = true;
                getUserDetailsInfo(this.searchForm).then(res=>{
                    if(res.code === "0000"){
                        let {records, total} = res.data;
                        this.$refs.memberInfoTable.updateTableData(records, total);
                    }
                });
            },
            checkChangeRemarks(v){
                if(this.postFlag!=="0"){
                    if(v === "0"){
                        this.show = true;
                        this.memberForm.changeRemarksRequired = false;
                    }else{
                        this.show = false;
                        this.memberForm.changeRemarksRequired = true;
                        this.memberForm.changeRemarks = "";
                    }
                }
            },
            //代理人
            cancelTaskHandler(){
                this.taskHandlerChangeVisible = false;
            },
            searchName(){
                this.taskHandlerChangeVisible = true;
            },
            afterChangeOwner(row){
                this.memberForm.proxy = row.userRealName;
                this.memberForm.agent = row.username+","+row.userRealName;
                this.taskHandlerChangeVisible = false;
            },
            clearSelectDep() {
                this.memberForm.proxy = "";
                this.memberForm.agent = "";
            },
            //组长
            searchGroupLeader(){
                this.groupLeaderVisible = true;
            },
            clearGroupLeader() {
                this.memberForm.headman = "";
                this.memberForm.groupLeader = "";
            },
            cancelGroupLeader(){
                this.groupLeaderVisible = false;
            },
            getGroupLeader(row){
                this.memberForm.headman = row.userRealName;
                this.memberForm.groupLeader = row.username+","+row.userRealName;
                this.groupLeaderVisible = false;
            },
            //代理组长
            cancelAgentGroupLeader(){
                this.agentGroupLeaderVisible = false;
            },
            getAgentGroupLeader(row){
                this.memberForm.chargeHand = row.userRealName;
                this.memberForm.agentGroupLeader = row.username+","+row.userRealName;
                this.agentGroupLeaderVisible = false;
            },
            searchAgentGroupLeader(){
                this.agentGroupLeaderVisible = true;
            },
            clearAgentGroupLeader(){
                this.memberForm.chargeHand = "";
                this.memberForm.agentGroupLeader = "";
            }
        },
        computed: {
            defines() {
                return [
                    {
                        id: 'userCollocation',
                        fields: userCollocation
                    }
                ]
            }
        },
        mounted() {
            this.init();
            this.getRoleList();
        }
    }
</script>
<style>
    .agentClass input::-webkit-input-placeholder{
        color:black;
    }
</style>
